package com.zhl.media.app.mvp.ui.activity;

import android.Manifest;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.muddzdev.styleabletoast.StyleableToast;
import com.previewlibrary.GPreviewBuilder;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhl.media.app.R;
import com.zhl.media.app.di.component.DaggerPreviewComponent;
import com.zhl.media.app.di.module.PreviewModule;
import com.zhl.media.app.event.Event;
import com.zhl.media.app.greendao.MediaPhotoDao;
import com.zhl.media.app.greendao.MediaPositionDao;
import com.zhl.media.app.greendao.ProjDao;
import com.zhl.media.app.model.ImgInfo;
import com.zhl.media.app.model.MediaPhoto;
import com.zhl.media.app.model.MediaPosition;
import com.zhl.media.app.model.Proj;
import com.zhl.media.app.mvp.contract.PreviewContract;
import com.zhl.media.app.mvp.presenter.PreviewPresenter;
import com.zhl.media.app.utils.EntityManager;
import com.zhl.media.commonres.base.AppActivity;
import com.zhl.media.commonres.view.PublicTitleBar;
import com.zhl.media.commonsdk.core.RouterHub;
import com.zhl.media.commonsdk.enumeration.MediaCode;
import com.zhl.media.commonsdk.imgaEngine.config.CommonImageConfigImpl;
import com.zhl.media.commonsdk.utils.CameraUtil;
import com.zhl.media.commonsdk.utils.DeleteFileUtil;
import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import static com.jess.arms.utils.Preconditions.checkNotNull;

@Route(path = RouterHub.APP_PREVIEWACTIVITY)
public class PreviewActivity extends AppActivity<PreviewPresenter> implements PreviewContract.View,TakePhoto.TakeResultListener,InvokeListener {
    private MediaPosition media;
    private MediaPhotoDao mediaPhotoDao;
    @BindView(R.id.titleBar)
    public PublicTitleBar titleBar;
    @BindView(R.id.photo)
    public ImageView photo;
    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.addr)
    TextView addr;
    private AppComponent mAppComponent;
    private ImageLoader mImageLoader; //用于加载图片的管理类,默认使用 Glide,使用策略模式,可替换框架
    private MediaPhoto mediaPhoto;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private MediaPositionDao mediaPositionDao;
    private String projId;
    private ProjDao projDao;
    private Proj proj;
    private int action;
    private Proj building;
    private Proj unit;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerPreviewComponent.builder().appComponent(appComponent).previewModule(new PreviewModule(this)).build().inject(this);
    }
    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_preview;
    }
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            RxPermissions rxPermission = new RxPermissions(PreviewActivity.this);
            rxPermission .requestEach(Manifest.permission.ACCESS_COARSE_LOCATION) .subscribe(new Consumer<Permission>() {
                @Override
                public void accept(Permission permission) throws Exception {
                    if (permission.granted) {
                        init();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        StyleableToast.makeText(PreviewActivity.this, "必须打开权限!", Toast.LENGTH_LONG, R.style.mytoast).show();
                    } else {
                        StyleableToast.makeText(PreviewActivity.this, "必须打开权限!", Toast.LENGTH_LONG, R.style.mytoast).show();
                    }
                }
            });
        }else {
            init();
        }
    }
    private void init(){
        mAppComponent = ArmsUtils.obtainAppComponentFromContext(this);
        mImageLoader = mAppComponent.imageLoader();
        Intent i = getIntent();
        projId = i.getStringExtra("projId");
        String buildingId = i.getStringExtra("buildingId");
        String unitId = i.getStringExtra("unitId");
        action = i.getIntExtra("action",0);
        media = (MediaPosition)i.getSerializableExtra("media");
        projDao = EntityManager.getInstance(this).getProjDao();
        proj = projDao.queryBuilder().where(ProjDao.Properties.Id.eq(projId)).unique();
        building = projDao.queryBuilder().where(ProjDao.Properties.Id.eq(buildingId)).unique();
        unit = projDao.queryBuilder().where(ProjDao.Properties.Id.eq(unitId)).unique();
        mediaPhotoDao = EntityManager.getInstance(this).getMediaPhotoDao();
        mediaPositionDao = EntityManager.getInstance(this).getMediaPositionDao();
        mediaPhoto = mediaPhotoDao.queryBuilder().where(MediaPhotoDao.Properties.MediaId.eq(media.getId())).unique();
        titleBar.setTitle(media.getMediaName());
        if(action==1){
            //修改媒体位
            media.setStatus(MediaCode.YPZ);
            media.setStu(MediaCode.YPZ.getKey());
            mediaPositionDao.update(media);
            Event.postUpdateMtw();
            if(mediaPhoto.getReload()==1){
                proj.setYiNum(proj.getYiNum() + 1);
                building.setYiNum(building.getYiNum() + 1);
                unit.setYiNum(unit.getYiNum() + 1);
                projDao.update(proj);
                projDao.update(unit);
                projDao.update(building);
            }
            Event.postUpdateGzrwList();
            //通知待上传数更新
            Event.postUpdateDscNum();
            initLocation();
        }
        addr.setText(media.getProjectName());
        mImageLoader.loadImage(this, CommonImageConfigImpl.builder().url(mediaPhoto.getPhotoPath()).imageView(photo).build());
        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImgInfo imgInfo = new ImgInfo(mediaPhoto.getPhotoPath());
                Rect bounds = new Rect();
                photo.getGlobalVisibleRect(bounds);
                imgInfo.setBounds(bounds);
                GPreviewBuilder.from(PreviewActivity.this)
                        .setSingleData(imgInfo)
                        .setCurrentIndex(0)
                        .setSingleFling(true)
                        .setFullscreen(true)
                        .setDrag(false)
                        .setSingleShowType(false)
                        .setType(GPreviewBuilder.IndicatorType.Dot)//指示器类型
                        .start();//启动
            }
        });
        clickInit();
        setTime();
    }

    private void setTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 媒体位状态初始值才设置时间
        if(action==1){
            //设置拍摄时间
            mediaPhoto.setPhotoDate(new Date().getTime());
            mediaPhotoDao.update(mediaPhoto);
            date.setText("拍摄时间：" + sdf.format(mediaPhoto.getPhotoDate()));
        }else {
            date.setText("拍摄时间：" + sdf.format(mediaPhoto.getPhotoDate()));
        }
    }

    private void clickInit() {
        titleBar.setRight("重拍", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CameraUtil.takePhotoCompress(getTakePhoto());
            }
        });
    }

    private LocationClientOption initLocationConfig(){
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedLocationPoiList(true);
        option.setIsNeedAddress(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setOpenGps(true);
        option.setLocationNotify(false);
        option.setScanSpan(0);
        return option;
    }

    public void initLocation(){
        mLocationClient = new LocationClient(this);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        mLocationClient.setLocOption(initLocationConfig());
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            Notification.Builder builder = new Notification.Builder (this);
            Intent nfIntent = new Intent(this, MainActivity.class);
            builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                    .setContentTitle("正在进行后台定位") // 设置下拉列表里的标题
                    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                    .setContentText("后台定位通知") // 设置上下文内容
                    .setAutoCancel(true)
                    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
            Notification notification = null;
            notification = builder.build();
            notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
            mLocationClient.enableLocInForeground(1001, notification);// 调起前台定位
//            //停止前台定位服务：
            mLocationClient.disableLocInForeground(true);// 关闭前台定位，同时移除通知栏
        }
        mLocationClient.start();
    }
    @Override
    public void showLoading() {
    }
    @Override
    public void hideLoading() {
    }
    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }
    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }
    @Override
    public void killMyself() {
        finish();
    }



    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        DeleteFileUtil.deleteFile(mediaPhoto.getPhotoPath());
        mediaPhoto.setPhotoPath(result.getImage().getCompressPath());
        mediaPhoto.setLatitude(0);
        mediaPhoto.setLongitude(0);
        mediaPhoto.setPhotoDate(1);
        mediaPhotoDao.update(mediaPhoto);
        mImageLoader.loadImage(this, CommonImageConfigImpl.builder().url(mediaPhoto.getPhotoPath()).imageView(photo).build());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置拍摄时间
        mediaPhoto.setPhotoDate(new Date().getTime());
        mediaPhotoDao.update(mediaPhoto);
        date.setText("拍摄时间：" + sdf.format(mediaPhoto.getPhotoDate()));
        initLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLocationClient != null){
            mLocationClient.unRegisterLocationListener(myListener);
            mLocationClient.stop();
        }
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation){
            LogUtils.warnInfo("经纬度：" + bdLocation.getLatitude() +"," + bdLocation.getLongitude());
            mLocationClient.stop();
            if(bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType()==BDLocation.TypeOffLineLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
                if(bdLocation.getPoiList() != null){
                    mediaPhoto.setLatitude(bdLocation.getLatitude());
                    mediaPhoto.setLongitude(bdLocation.getLongitude());
                    mediaPhotoDao.update(mediaPhoto);
                }else {
                    addr.setText(media.getProjectName());
                    mediaPhoto.setLatitude(bdLocation.getLatitude());
                    mediaPhoto.setLongitude(bdLocation.getLongitude());
                    mediaPhotoDao.update(mediaPhoto);
                }
            }
        }
    }
}
